import React, {Component} from 'react';
import {View, Text, TextInput, TouchableOpacity, Image, ScrollView} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import Header from "../../../../components/header";
import {pxToDp} from "../../../../utils/styleKits";
import icon from "../../../../utils/icon";
import Geo from "../../../../utils/Geo";
import {Toast, ActionSheet} from 'teaset';
import Emotions from "../../../../components/Emotions.js";
import {observer, inject} from "mobx-react";
import PublishStore from "../../../../mobx/publist";
import {EMOTIONS_ZHCN} from "../../../../face/datasource";

// 发动态页面
@inject("PublishStore")
@observer
class Publish extends Component {
  state = {
    location: '',
    tmpImgList: [], // 选择的图片
    isEmotions: false, // 是否显示表情图片
    text: '', // 用户输入的文字, 没有转化成中文的表情符
    textZhCn: '' // 中文表情符
  };

  constructor(props){
    super(props);
    this.inputRef = React.createRef()
  }

  render() {
    let {tmpImgList, isEmotions, textZhCn, location} = this.state;
    return (
      <View style={{flex: 1}}>
        <Header title={'发动态'} leftTitle={'取消'} rightTitle={'发帖'} rightPress={this.postMessage}/>

        <View style={{flex: 1}}>
          {/*输入框*/}
          <TextInput ref={this.inputRef} multiline style={{height: pxToDp(250), textAlignVertical: 'top'}} value={textZhCn}
                     placeholder={'请填写动态(140字以内)'} onChangeText={text => {
            this.setState({text,textZhCn:text})
          }}/>

          {/*定位*/}
          <TouchableOpacity onPress={this.getLocation}
                            style={{marginRight: pxToDp(10), flexDirection: 'row', justifyContent: 'flex-end'}}>
            <Text style={{
              color: '#666',
              fontFamily: 'iconfont',
              marginRight: pxToDp(10),
              fontSize: pxToDp(24)
            }}>{icon.iconlocation}</Text>
            <Text style={{color: '#666'}}>{location.length>0?location.split('区')[1]:'你在哪里？'}</Text>
          </TouchableOpacity>

          {/*显示选择的图片*/}
          <View style={{height: tmpImgList.length > 0 ? pxToDp(60) : 0}}>
            <ScrollView horizontal>
              {
                tmpImgList.map((item, i) => {
                  return <TouchableOpacity onPress={this.showRemove.bind(this, i)}>
                    <Image key={i} source={{uri: item.uri}}
                           style={{width: pxToDp(60), height: '100%', margin: pxToDp(10)}}/>
                  </TouchableOpacity>
                })
              }
            </ScrollView>
          </View>

          {/*图片、表情*/}
          <View style={{
            height: pxToDp(60), backgroundColor: '#ddd', marginTop: pxToDp(10), alignItems: 'center',
            flexDirection: 'row', padding: pxToDp(20)
          }}>
            <TouchableOpacity onPress={this.showImagePicker}>
              <Text style={{
                fontFamily: 'iconfont',
                fontSize: pxToDp(30),
                color: '#666',
                marginRight: pxToDp(50)
              }}>{icon.icontupian}</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={()=>{this.setState({isEmotions: !isEmotions})}}>
              <Text style={{fontFamily: 'iconfont', fontSize: pxToDp(30), color: '#666'}}>{icon.iconbiaoqing}</Text>
            </TouchableOpacity>
          </View>

          {/*显示表情*/}
          <Emotions isEmotions={isEmotions} onPress={this.textAddEmotion}/>

        </View>
      </View>
    );
  }


  // 发帖
  postMessage = () => {
    let {text} = this.state;
    //提交数据

    // 返回
    Toast.smile('发帖成功');
    this.props.PublishStore.setMessage(text);
    // reset可刷新跳转的页面
    this.props.navigation.reset({
      routes:[{name:'tabBar',params:{pagename:'Group'}}]
    })
  };

  // 将用户选择的 表情符中文含义 插入到input框中
  textAddEmotion = (emotionsZhCn, k) => {
    let {text,textZhCn} = this.state;

    this.setState({
      text: text + k,
      textZhCn: textZhCn + emotionsZhCn,
    });

  };

  //点击图片，弹出提示框
  showRemove = (i) => {
    let items = [
      {title: '删除', onPress: () => this.removeImg(i)},
    ];
    let cancelItem = {title: '取消'};
    ActionSheet.show(items, cancelItem);
  };

  // 删除图片
  removeImg = (i) => {
    let {tmpImgList} = this.state;
    tmpImgList.splice(i, 1);
    this.setState({
      tmpImgList
    });
    Toast.smile('删除成功')
  };

  // 选择图片
  showImagePicker = () => {
    const options = {
      title: '选择图片',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '从本地选择图片',
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };

    ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        let {tmpImgList} = this.state;
        if (tmpImgList.length >= 9) {
          Toast.message('图片数量不能大于9');
          return;
        }

        tmpImgList.push(response);
        this.setState({
          tmpImgList,
        });
      }

    })
  };

  // 获取定位
  getLocation = async () => {
    let res = await Geo.getCityByLocation();
    if (res.info === 'OK') {
      this.setState({
        location: res.regeocode.formatted_address,
      })
    }
  };
}

export default Publish;